import {FaRegComment} from "react-icons/fa"
import {BiRepost} from "react-icons/bi"
import {FaRegHeart} from "react-icons/fa"
import {FaRegBookmark} from "react-icons/fa"
import {FaTrash} from "react-icons/fa"
import {useState} from "react"
import {Link} from "react-router-dom"
import {useMutation,useQuery,useQueryClient} from "@tanstack/react-query"
import {toast} from "react-hot-toast"

import {LoadingSpinner} from "./LoadingSpinner"
import {formatPutoutDate} from "../../utils/date"

const Putout = ({post}) => {
    const [comment, setComment] = useState("")
    const {data: authUser} = useQuery({queryKey: ["authUser"]})
    const queryClient = useQueryClient()
    const putoutOwner = putout.user
    const isLiked = putout.likes.includes(authUser._id)

    const isMyPutout = authUser._id === putout.user._id

    const formattedDate = formatPutoutDate(putout.createdAt)

    const {
        mutate: deletePutout,
        isPending: isDeleting
    } = useMutation({
        mutationFn: async() => {
            try {
                const res = await fetch(`/api/putouts/${putout._id}`, {
                    method: "DELETE",
                })

                const data = await res.json()
                if (!res.ok) {
                    throw new Error(data.error || "Something went wrong")
                }
                return data
            }catch(error) {
                throw new Error("Error in Putout.jsx: "+error)
            }
        },

        onSuccess: () => {
            toast.success("Putout deleted successfully")
            queryClient.invalidateQueries({
                queryKey: ["putouts"]
            })
        },
    })

    const {mutate: likePutout, isPending: isLiking} = useMutation({
        mutationFn: async () => {
            try {
                const res = await fetch(`/api/putouts/like/${putout._id}`, {
                    method: "POST",
                })
                const data = await res.json()
                if (!res.ok) {
                    throw new Error(data.error || "Something went wrong")
                }
                return data
            }catch(error) {
                throw new Error("Error in Putout.jsx: "+ error)
            }
        },

        onSuccess: (updatedLikes) => {
            queryClient.setQueryData(["putouts"], (oldData) => {
                return oldData.map((p) => {
                    if (p._id === putout._id) {
                        return {...p, likes: updatedLikes}
                    }
                    return p
                })
            })
        },

        onError: (error) => {
            toast.error(error.message)
        },
    })

    const {mutate: commentPutout, isPending: isCommenting} = useMutation({
        mutationFn: async () => {
            try {
                const res = await fetch(`/api/putouts/comment/${putout._id}`, {
                    method: "POST",
                    headers: {
                        "Content-Type": "application/json",
                    },
                    body: JSON.stringify({text: comment})
                })

                const data = await res.json()

                if (!res.ok) {
                    throw new Error(data.error || "Something went wrong")
                }
                return data
            }catch(error) {
                throw new Error("Error in Putout.jsx: " + error)
            }
        },

        onSuccess: () => {
            toast.success("Comment on putout successfully")
            setComment("")
            queryClient.invalidateQueries({queryKey: ["putouts"]})
        },

        onError: (error) => {
            toast.error(error.message)
        }
    })

    const handleDeletePutout = () => {
        deletePutout()
    }

    const handlePutoutComment = (e) => {
        e.preventDefault()
        if (isCommenting) return
        commentPutout()
    }

    const handleLikePutout = () => {
        if (isLiking) return
        likePutout()
    }

    return (
    <>
        {/* DIV ROOT */}
        <div className="flex gap-2 items-start p-4 border-b border-gray-700">
            {/* DIV 1 */}
            <div className='avatar'>
                <Link to={`/profile/${putoutOwner.username}`} 
                    className="w-8 rounded-full overflow-hidden">
                    <img src={putoutOwner.profileImg || "/avatar-placeholder.png"} />
                </Link>
            </div>
            {/* END DIV 1 */}

            {/* DIV 2 */}
            <div className="flex flex-col flex-1">
                <div className="flex gap-2 items-center">
                    <Link to={`/profile/${putoutOwner.username}`}
                        className="font-bold">
                        {putoutOwner.fullName}
                    </Link>
                    <span className="text-gray-700 flex gap-1 text-sm">
                        <Link to={`/profile/${putoutOwner.username}`}>@{putoutOwner.username}
                        </Link>
                        <span>
                        </span>
                        <span>
                            {formattedDate}
                        </span>
                    </span>
                    {isMyPutout && (
                        <span className="flex justify-end flex-1">
                            {!isDeleting && (
                                <FaTrash className="cursor-pointer hover:text-red-500"
                                    onClick={handleDeletePutout}/>)}
                            {isDeleting && <LoadingSpinner size="sm" />}
                        </span>
                    )}
                </div>
                <div className="flex flex-col gap-3 overflow-hidden">
                    <span>
                        {putout.text}
                    </span>
                    {putout.img && (
                        <img src={putout.img}
                            className="h-80 object-contain rounded-lg border border-gray-700"
                            alt=''
                        />
                    )}
                </div>
                <div className="flex justify-between mt-3">
                    <div className="flex gap-4 items-center w-2/3 justify-between">
                    {/* TODO:  */}
                    </div>
                </div>
            </div>
            {/* END DIV 2 */}
        </div>
        {/* DIV ROOT */}
    </>
    )
}

export default Putout